package com.sport.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sport.service.CaptchaService;
import com.sport.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {
    private final StringRedisTemplate stringRedisTemplate;
    private final SmsUtil smsUtil;

    public CaptchaServiceImpl(StringRedisTemplate stringRedisTemplate, SmsUtil smsUtil) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.smsUtil = smsUtil;
    }

    @Override
    public void getSmsCaptcha(String phone) {
        String hashKey = "login:sms:captcha:" + phone;
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(hashKey);

        // 初始检查
        String lastSendTimestamp = hashOps.get("lastSendTimestamp");
        String sendCount = hashOps.get("sendCount");
        String captcha = hashOps.get("captcha");
        hashOps.expire(5, TimeUnit.MINUTES); // 设置过期时间为5分钟

        // 判断发送次数是否超过限制
        if (StringUtils.isNotBlank(sendCount) && Integer.parseInt(sendCount) >= 5) {
            hashOps.expire(24, TimeUnit.HOURS); // 重新设置过期时间为24H
            throw new RuntimeException("发送次数过多，请24H后再试");
        }

        // 判断发送频率是否过高
        if (StringUtils.isNotBlank(lastSendTimestamp)) {
            long lastSendTime = Long.parseLong(lastSendTimestamp);
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - lastSendTime;
            long interval = 60 * 1000; // 60秒
            if (elapsedTime < interval) {
                throw new RuntimeException("发送短信过于频繁，请稍后再试");
            }
        }

        // 更新发送次数
        int newSendCount = StringUtils.isNotBlank(sendCount) ? Integer.parseInt(sendCount) + 1 : 1;

        // 生成新验证码
        if (StringUtils.isBlank(captcha)) {
            captcha = RandomStringUtils.randomNumeric(6);
        }

        // 发送短信
        try {
            if (!smsUtil.sendSms(phone, captcha)) {
                log.error("发送短信失败, 手机号: {}, 验证码: {}", phone, captcha);
                throw new RuntimeException("发送短信失败");
            }
        } catch (Exception e) {
            log.error("发送短信过程中发生异常", e);
            throw new RuntimeException("发送短信失败", e);
        }


        // 更新 Redis 中的信息
        hashOps.put("captcha", captcha);
        hashOps.put("lastSendTimestamp", String.valueOf(System.currentTimeMillis()));
        hashOps.put("sendCount", String.valueOf(newSendCount));
    }
}
